import Router from 'koa-router';
import ReplyTemplate from '../models/replyTemplate';
import tokenAuth from '../middleware/tokenAuth';

const router = new Router({
  prefix: '/api/replyTemplates',
});
router.use(tokenAuth());

/**
 * 创建回复模板
 * input => {
 *  template:String,
 *  template_group:ObjectId/ref TemplateGroup
 * }
 */
router.post('/create', async (ctx /* ,next */) => {
  const input = ctx.request.body;
  const replyTemplate = new ReplyTemplate(input);
  await replyTemplate.save();

  ctx.body = {
    ok: true,
    reply_template: replyTemplate,
  };
});

/**
 * 更新回复模板
 * :id => templateId
 * input => {
 *  anyField.
 * }
 */
router.post('/:id/update', async (ctx /* ,next */) => {
  const input = ctx.request.body;
  const replyTemplateId = ctx.params.id;
  const replyTemplate = await ReplyTemplate.findByIdAndUpdate(
    replyTemplateId,
    input,
    { new: true },
  );

  ctx.body = {
    ok: true,
    reply_template: replyTemplate,
  };
});

/**
 * 删除回复模板
 * :id => templateId
 */
router.post('/:id/delete', async (ctx /* ,next */) => {
  const replyTemplateId = ctx.params.id;
  const replyTemplate = await ReplyTemplate.findByIdAndRemove(replyTemplateId);

  ctx.body = {
    ok: true,
    reply_template: replyTemplate,
  };
});

export default router;
